import { ref, reactive, inject } from "vue";
import { useProjectStore } from '../../../store/useProjectStore'

interface Tree {
    id: string;
    label: string;
    value: string;
    children?: Tree[];
}

export const useProjectRequirement = (currentPage: any, pageSize: any) => {
    //获取API配置
    const API = inject("API") as any;
    const ApiConfig = inject("ApiConfig") as any;

    const requirementData = reactive(
        {
            total: 0,
            tableData: [],
            queryCondition: {
                projectName: '',
                status: null,
            },
            tree: ref<Tree[]>([])
        }
    );

    const projectStore = useProjectStore();

    //编制需求
    const formulateRequirement = async () => {
        try {
            const response = await API.request(
                ApiConfig.Methods.POST,
                ApiConfig.PATH.Project.FormulateProjectRequirement,
                projectStore.requirementModel
            );
            if (response.status == "200" && response.data.code == "200") {
                return true;
            }
        } catch (error) {
            console.error(error);
        }
        return false;
    }

    //根据项目ID获取项目需求
    const getRequirementDetailByProjectId = async (projectId) => {
        try {
            const response = await API.request(
                ApiConfig.Methods.GET,
                ApiConfig.PATH.Project.GetRequirementDetailByProjectId,
                { projectId: projectId }
            );

            if (response.status == "200" && response.data.code == "200") {
                projectStore.requirementModel = response.data.data;
            }
        } catch (error) {
            console.error(error);
        }
    }

     //根据项目ID获取项目需求基本信息
     const getRequirementEntityByProjectId = async (projectId) => {
        try {
            const response = await API.request(
                ApiConfig.Methods.GET,
                ApiConfig.PATH.Project.GetRequirementEntityByProjectId,
                { projectId: projectId }
            );

            if (response.status == "200" && response.data.code == "200") {
                projectStore.requirementModel = response.data.data;
            }
        } catch (error) {
            console.error(error);
        }
    }

    //根据需求ID获取需求详情
    const getRequirementDetailByRequirementId = async (rId) => {
        try {
            const response = await API.request(
                ApiConfig.Methods.GET,
                ApiConfig.PATH.Project.GetRequirementDetailByRequirementId,
                { requirementId: rId }
            );

            if (response.status == "200" && response.data.code == "200") {
                projectStore.requirementModel.requirements = response.data.data;
            }
        } catch (error) {
            console.error(error);
        }
    }

    //查询
    const getProjectRequirements = async () => {
        try {
            const response = await API.request(
                ApiConfig.Methods.POST,
                ApiConfig.PATH.Project.GetProjectRequirements,
                {
                    pageIndex: currentPage.value,
                    pageSize: pageSize.value,
                    condition: { projectName: requirementData.queryCondition.projectName, status: requirementData.queryCondition.status },
                }
            );
            if (response.status == "200" && response.data.code == "200") {
                requirementData.tableData = response.data.data;
                requirementData.total = response.data.count;
            }
        } catch (error) {
            console.error(error);
        }
    };

    //获取项目对应的需求树
    const getProjectRequirementTree = async (projectId) => {
        try {
            const response = await API.request(
                ApiConfig.Methods.GET,
                ApiConfig.PATH.Project.GetProjectRequirementTree,
                {
                    projectId: projectId
                }
            );
            if (response.status == "200" && response.data.code == "200") {

                // 递归处理功能
                const transformFeatureData = (features) => {
                    return features.map((feature) => {
                        return {
                            id: feature.id,
                            label: feature.title, // 假设 feature 有个 name 属性
                            value: feature.title,
                            type: 'feature',
                            rId: feature.rId,
                            rName: feature.rName,
                            // 如果 feature 有子项则递归处理
                            children: feature.childFeatures
                                ? transformFeatureData(feature.childFeatures)
                                : [], // 若没有子项则为空数组
                        };
                    });
                };

                const transformOrgData: any = (childRequirementInfos: any[]) => {
                    return childRequirementInfos.map((requirement) => {
                        // 处理 RequirementFeatures 并将其转换为树节点
                        const featureNodes = requirement.childFeatures
                            ? transformFeatureData(requirement.childFeatures)
                            : [];

                        // 处理子需求并递归构造树
                        const childNodes = requirement.childRequirementInfos
                            ? transformOrgData(requirement.childRequirementInfos)
                            : [];

                        // 返回当前需求节点，同时将 RequirementFeatures 和子需求都放在 children 中
                        return {
                            id: requirement.id,
                            label: requirement.title,
                            value: requirement.title,
                            type: 'requirement', // 标记为需求节点
                            rId: requirement.id,
                            rName: requirement.title,
                            children: [...childNodes, ...featureNodes], // 将子需求和 features 合并到 children 中
                        };
                    });
                    // return childRequirementInfos.map((requirement) => {
                    //     return {
                    //         id: requirement.id,
                    //         label: requirement.title,
                    //         value: requirement.title,
                    //         children: requirement.childRequirementInfos
                    //             ? transformOrgData(requirement.childRequirementInfos)
                    //             : [],
                    //     };
                    // });
                };
                requirementData.tree = transformOrgData(response.data.data);
            }
        } catch (error) {
            console.error(error);
        }
    };

    //更新项目需求指定信息
    const updateRequirementMainSpecificContent = async () => {
        try {
            const response = await API.request(
                ApiConfig.Methods.POST,
                ApiConfig.PATH.Project.UpdateRequirementMainSpecificContent,
                projectStore.requirementModel
            );
            if (response.status == "200" && response.data.code == "200") {
                return true;
            }
        } catch (error) {
            console.error(error);
        }
        return false;
    }

    //根据需求主记录ID获取需求
    const getRequirementDetailById = async (id) => {
        try {
            const response = await API.request(
                ApiConfig.Methods.GET,
                ApiConfig.PATH.Project.GetRequirementDetailById,
                { id: id }
            );

            if (response.status == "200" && response.data.code == "200") {
                projectStore.requirementModel = response.data.data;
            }
        } catch (error) {
            console.error(error);
        }
    }

    return {
        requirementData,
        projectStore,
        formulateRequirement,
        getRequirementDetailByProjectId,
        getRequirementEntityByProjectId,
        getProjectRequirements,
        getProjectRequirementTree,
        updateRequirementMainSpecificContent,
        getRequirementDetailById,
        getRequirementDetailByRequirementId
    };
};